﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace VoiceControl
{
    public partial class Login : PhoneApplicationPage
    {
        public Login()
        {
            InitializeComponent();
        }

        private void BB_Login_Click(object sender, EventArgs e)
        {
            LoadingPanel.Visibility = Visibility.Visible;
            LoadHttp();
        }

        void LoadHttp()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://222.24.63.111:88/JspUpDownTest/servlet/JsonFile");
            request.BeginGetResponse(new AsyncCallback(getResponse), request);
        }

        void getResponse(IAsyncResult result)
        {
            HttpWebRequest req = (HttpWebRequest)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(result);
            Stream stream = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(stream))
            {
                string str = reader.ReadToEnd();
                Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        JArray array = JArray.Parse(str);
                        if (App.FileData.Count != 0)
                        { 
                            App.FileData.Clear();
                            App.FileNames.Clear();
                        }
                        foreach (var item in array)
                        {
                            App.FileData.Add(new FileInfo
                            {
                                Name = (string)item["fileName"],
                                Size = (string)item["fileSize"]
                            });
                            string tmp = ((string)item["fileName"]).Substring(0, ((string)item["fileName"]).IndexOf("."));
                            App.FileNames.Add(tmp);
                            App.EmailFile.Add("给金航发送" + tmp);
                        }
                        this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    }
                    catch
                    {
                        new App.ToastTips("文件列表获取失败");
                    }
                    finally
                    {
                        LoadingPanel.Visibility = Visibility.Collapsed;
                    }
                });
            }
        }
    }
}